import { ccDict } from '@/api/dataDict'
import { numToString, strToNumber, filtersRaw, parseTime, date24 } from '@/utils'
import aeraCode from '@/utils/areaCode'
import { exportExcelFile } from '@/utils/dataToExcel'
import { Message } from 'element-ui'
// 如果正式环境，屏蔽console
window._console = window.console
if (process.env.NODE_ENV !== 'development') {
  const t = {}
  for (const key of Object.keys(window.console)) {
    t[key] = () => {}
  }
  window.console = t
}

// 区分组织： 服务支持部（14），电商管理部(25)，销售管理部（23），销售财务部(24)，销售管理三部（13）
const client = '14'
const finance = '24'
const shop = '25'
const customerCare = '27' // 客满关怀组
const sale = '23'
const sale3 = '13'
// 新增了一个组织：29客户管理部
const customerManagement = '29'
export default {
  install(Vue, { store, router, duration }) {
    // 判断用户是否在指定组织里面
    function inGroup(groupNo) {
      if (groupNo === undefined) {
        return false
      }
      const g = (store.state.user.userCache.businessGroupList || []).map(e => e.groupNo)
      if (typeof groupNo !== 'object') {
        if (/,/g.test(groupNo)) {
          groupNo = groupNo.split(',')
        } else {
          groupNo = [groupNo]
        }
      }
      for (const item of g) {
        for (const i of groupNo) {
          if (item.toString() === i.toString()) {
            return true
          }
        }
      }
      return false
    }
    // 判断用户部门
    function inDept(deptNo) {
      if (deptNo === undefined) {
        return false
      }
      const d = (store.state.user.userCache.departmentInfoList || []).map(e => e.deptNo)
      if (typeof deptNo !== 'object') {
        if (/,/g.test(deptNo)) {
          deptNo = deptNo.split(',')
        } else {
          deptNo = [deptNo]
        }
      }
      for (const item of d) {
        for (const i of deptNo) {
          if (item.toString() === i.toString()) {
            return true
          }
        }
      }
      return false
    }
    function isClient() {
      return inDept(client)
    }
    function isFinance() {
      return inDept(finance)
    }
    function isShop() {
      return inDept(shop)
    }
    function isCustomerCare() {
      return inDept(customerCare)
    }
    function isSale() {
      return inDept(sale)
    }
    function isSale3() {
      return inDept(sale3)
    }
    function isCustomerManagement() {
      return inDept(customerManagement)
    }
    // 是否是当前登录用户(根据accountNo判断)
    function isAccount(accountNo) {
      if (accountNo === undefined) {
        return false
      }
      return store.state.user.userCache.accountNo.toString() === accountNo.toString()
    }
    // 是否是当前登录用户
    function slef(accountNo) {
      if (accountNo === undefined) {
        return false
      }
      return store.state.user.userCache.accountNo.toString() === accountNo.toString()
    }
    Object.defineProperties(Vue.prototype, {
      '$inGroup': {
        value: inGroup
      },
      '$inDept': {
        value: inDept
      },
      '$self': {
        value: slef
      },
      '$isAccount': {
        value: isAccount
      },
      '$isClient': {
        value: isClient
      },
      '$isFinance': {
        value: isFinance
      },
      '$isShop': {
        value: isShop
      },
      '$isCustomerCare': {
        value: isCustomerCare
      },
      '$isSale': {
        value: isSale
      },
      '$isSale3': {
        value: isSale3
      },
      '$isCustomerManagement': {
        value: isCustomerManagement
      },
      '$client': {
        value: client
      },
      '$finance': {
        value: finance
      },
      '$shop': {
        value: shop
      },
      '$customerCare': {
        value: customerCare
      },
      '$sale': {
        value: sale
      },
      '$sale3': {
        value: sale3
      },
      '$customerManagement': {
        value: customerManagement
      }
    })
    // 是否是应急登录
    Object.defineProperty(Vue.prototype, '$emergency', { value: process.env.VUE_APP_BASE_EMERGENCY })
    // 是否是开发环境
    Object.defineProperty(Vue.prototype, '$dev', { value: process.env.NODE_ENV === 'development' })
    // 手机号去掉前缀
    function prefixTrim(tel, prefix) {
      if (tel === undefined || tel === null) return ''
      if (typeof tel === 'string') {
        tel = tel.trim()
      }
      // 呼出有前缀 // 可能会加0
      if (prefix) {
        tel = tel.replace(prefix, '')
      }
      // 呼入座机号有前缀
      if (tel.length >= 11 && (aeraCode.includes(tel.substr(0, 3) || aeraCode.includes(tel.substr(0, 4))))) {
        return tel
      }
      // 区分手机和座机
      // 带有0的手机号
      if (/^01\d{10}$/.test(tel)) {
        return tel.slice(tel.length - 11)
      }
      // 检查座机
      if (/^0\d{2,3}\d{7,8}$/.test(tel)) {
        return tel
      }
      // 手机
      if (/^1\d{10}$/.test(tel)) {
        return tel
      }
      const _tel = tel.slice(tel.length - 11)
      if (/^1\d{10}$/.test(_tel)) {
        return _tel
      }
      // if (/[^-]/g.test(tel) && tel.length > 11) {
      //   tel = tel.slice(tel.length - 11)
      // }
      return tel
    }
    Object.defineProperty(Vue.prototype, '$prefixTrim', { value: prefixTrim })
    // 根据字典和值取对应值
    function getDictValue(dictType, dictCode) {
      return ccDict(dictType).then(res => {
        for (const item of res.data) {
          if (item.dictCode === dictCode) {
            return item.dictName ? item.dictName : '--'
          }
        }
      })
    }
    Object.defineProperty(Vue.prototype, '$getDictValue', { value: getDictValue })
    function getNameByDataDict(dictCode, dataDict, defStr = '') {
      if (dictCode === undefined || dictCode === null) {
        return defStr
      }
      for (const item of dataDict) {
        if (item.dictCode.toString() === dictCode.toString()) {
          return item.dictName
        }
      }
      return defStr
    }
    Object.defineProperty(Vue.prototype, '$getNameByDataDict', { value: getNameByDataDict })
    Object.defineProperty(Vue.prototype, '$numToString', { value: numToString })
    Object.defineProperty(Vue.prototype, '$strToNumber', { value: strToNumber })
    // 关闭当前标签页
    function closePage(route, to) {
      return store.dispatch('tagsView/delView', route || router.currentRoute).then(({ visitedViews, cachedViews, visitedQueue }) => {
        const routeQueue = visitedQueue.pop()
        const routeView = visitedViews.pop()
        if (to) {
          router.push(to)
        } else if (routeQueue) {
          router.push(routeQueue)
        } else if (routeView) {
          router.push(routeView)
        } else {
          router.push('/')
        }
      })
    }
    Object.defineProperty(Vue.prototype, '$closePage', { value: closePage })
    // 更新tagView数据
    function updateTagView(route) {
      store.dispatch('tagsView/updateVisitedView', route)
    }
    Object.defineProperty(Vue.prototype, '$updateTagView', { value: updateTagView })
    // 导出
    Object.defineProperty(Vue.prototype, '$exportExcelFile', { value: exportExcelFile })
    // 复制
    function copyText(text) {
      const input = document.createElement('input')
      input.type = 'textarea'
      input.value = text
      input.style.height = '2em'
      input.style.width = '2em'
      input.style.position = 'fixed'
      input.style.top = '-100px'
      input.style.left = '-100px'
      document.body.append(input)
      input.select()
      const success = document.execCommand('Copy')
      if (success) {
        this.$message.success(`已复制到剪贴板！`)
      }
      document.body.removeChild(input)
    }
    Object.defineProperty(Vue.prototype, '$copyText', { value: copyText })
    /** 防抖 */
    function debounce(fn, ctx, delay = 200) {
      let id = null
      return (...args) => {
        if (id !== null) {
          clearTimeout(id)
        }
        return new Promise((resolve, reject) => {
          id = setTimeout(() => {
            const result = fn.apply(ctx, args)
            if (result instanceof Promise) {
              result.then(res => resolve(res)).catch(err => reject(err))
            } else {
              resolve(result)
            }
            id = null
          }, delay)
        })
      }
    }
    Object.defineProperty(Vue.prototype, '$debounce', { value: debounce })
    // 验证判空
    function validateNone(v) {
      if (v === '' || v === undefined || v === null || (typeof v === 'object' && Object.keys(v).length <= 0)) {
        return true
      }
      return false
    }
    Object.defineProperty(Vue.prototype, '$validateNone', { value: validateNone })
    function genRule(opertor, keys = []) {
      return {
        opertor,
        keys
      }
    }
    Object.defineProperty(Vue.prototype, '$genRule', { value: genRule })
    // 处理otherFilters
    function genOtherFilters(formData, ...rules) {
      const otherFilters = []
      // eslint-disable-next-line prefer-const
      for (let [k, v] of Object.entries(formData)) {
        if (validateNone(v)) {
          continue
        }
        if (v instanceof Array) {
          if (v.length === 2 && v.every(e => (e instanceof Date))) {
            otherFilters.push(filtersRaw(k, parseTime(v[0], '{y}-{m}-{d}'), '>='))
            otherFilters.push(filtersRaw(k, parseTime(date24(v[1]), '{y}-{m}-{d}'), '<'))
            continue
          } else {
            v = `[${v.join(',')}]`
          }
        }
        let flag = true
        for (const rv of rules) {
          if (rv.keys.includes(k)) {
            otherFilters.push(filtersRaw(k, v, rv.opertor))
            flag = false
            break
          }
        }
        if (flag) {
          otherFilters.push(filtersRaw(k, v, 'like'))
        }
      }
      return otherFilters
    }
    Object.defineProperty(Vue.prototype, '$genOtherFilters', { value: genOtherFilters })
    // 处理otherRaw
    function genOtherRaw(formData, keys = []) {
      const otherRaw = {}
      for (const k of keys) {
        const v = formData[k]
        if (v === undefined || v === '' || v === null || (typeof v === 'object' && Object.keys(v).length <= 0)) {
          continue
        }
        if (v instanceof Array) {
          otherRaw[k] = `[${v.join(',')}]`
        } else if (v instanceof Date) {
          otherRaw[k] = parseTime(v, '{yyyy}-{mm}-{dd}')
        } else if (Object.prototype.toString.call(v) === '[object Object]') {
          otherRaw[k] = JSON.stringify(v)
        } else {
          otherRaw[k] = v
        }
      }
      return otherRaw
    }
    Object.defineProperty(Vue.prototype, '$genOtherRaw', { value: genOtherRaw })
    // 检测是否选中或单选
    function checkSelected(selected, single = true) {
      return new Promise((resolve, reject) => {
        if (selected.length <= 0) {
          Message.warning('请选择一条数据')
          reject()
        } else if (selected.length > 1 && single) {
          Message.warning('该操作仅可单选')
          reject()
        } else {
          resolve()
        }
      })
    }
    Object.defineProperty(Vue.prototype, '$checkSelected', { value: checkSelected })
    // 统一修改提示时长
    const message = Vue.prototype.$message
    Vue.prototype.$message = function(arg) {
      if (typeof arg === 'object') {
        arg.duration = duration || 2000
        arg.showClose = true
        message(arg)
      } else {
        const opt = {
          message: arg,
          duration: duration || 2000,
          showClose: true
        }
        message(opt)
      }
    }
    const fnList = ['success', 'warning', 'info', 'error']
    fnList.forEach(e => {
      const fn = message[e]
      Vue.prototype.$message[e] = function(arg) {
        if (typeof arg === 'object') {
          arg.duration = duration || 2000
          arg.showClose = true
          fn(arg)
        } else {
          const opt = {
            message: arg,
            duration: duration || 2000,
            showClose: true
          }
          fn(opt)
        }
      }
    })

    // ========== 话务 ===========
    // 获取外呼类型
    function getCallOutType(source) {
      // 检查商机是否是字节系的
      if ([3, 17, '3', '17', 'DouyinZhibo'].includes(source)) {
        return 2
      }
      // 检查商机是否是腾讯系的
      if (['YouJuWXAd', '1'].includes(source)) {
        return 3
      }
      // 检查商机是否是快手的
      if ([13, '13'].includes(source)) {
        return 4
      }
      return 1
    }
    Object.defineProperty(Vue.prototype, '$getCallOutType', {
      value: getCallOutType
    })
    // 根据外呼类型返回数据
    Object.defineProperty(Vue.prototype, '$callOutChoice', {
      value: (source, mapObj) => {
        return mapObj(getCallOutType(source))
      }
    })
    // 获取外呼名称
    Object.defineProperty(Vue.prototype, '$getCallOutName', {
      value: (source,) => {
        return {
          1: '华为平台',
          2: '字节飞鱼',
          3: '腾讯',
          4: '快手'
        }[(getCallOutType(source))]
      }
    })
    // 是华为外呼
    Object.defineProperty(Vue.prototype, '$isHuaWei', {
      value: source => {
        return [1, '1'].includes(getCallOutType(source))
      }
    })
    // 获取运营商
    Object.defineProperty(Vue.prototype, '$getTelecomOperator', {
      value: source => {
        return {
          1: null,
          2: 5,
          3: 6,
          4: 7 // TODO:根据具体情况修改
        }[(getCallOutType(source))]
      }
    })
    Object.defineProperty(Vue.prototype, '$getCallSource', {
      value: function() {
        return store.state.user.userCache.callPlatform === '02' ? '5' : '1'
      }
    })
  }
}
